//
//  ShareSdkUtil.m
//  p4
//
//  Created by Javen Wang on 1/23/15.
//  Copyright (c) 2015 me.yang-yuxin. All rights reserved.
//

#import "EFSShareManager.h"

#import <YTXRequest/YTXRequestConfig.h>
#import <ShareSDK/ShareSDK.h>
#import <SinaWeiboConnection/ISSSinaWeiboApp.h>
#import "EFSPreloadConfig.h"

#define SHARE_SDK_ERROR_DOMAIN @"EFS"
typedef void(^SinaPublishResult) (SSResponseState state, id<ISSPlatformShareInfo> status, CMErrorInfo *error);

@implementation EFSShareManager

+ (RACSignal *)oauthForPlatform:(ShareType)shareType {
    RACReplaySubject *subject = [RACReplaySubject subject];
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    [ShareSDK getUserInfoWithType:shareType
                      authOptions:authOptions
                           result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
                               if (result)
                               {
                                   NSString *platform;
                                   switch (shareType) {
                                       case ShareTypeSinaWeibo:
                                           platform = @"SinaWeibo";
                                           break;
                                       case ShareTypeQQSpace:
                                           platform = @"QZone";
                                           break;
                                       case ShareTypeWeixiSession:
                                           platform = @"Wechat";
                                           break;
                                       default:
                                           platform = @"Unknown";
                                           break;
                                   }
                                   NSDictionary *userInfoParam = @{
                                                                   @"nickname":objectOrNull([userInfo nickname]),
                                                                   @"sex":@([userInfo gender]),
                                                                   @"birthday":objectOrNull([userInfo birthday])
                                                                   };
                                   NSDictionary *authenticationParam = @{
                                                                         @"openId": [[userInfo credential] uid],
                                                                         @"accessToken": [[userInfo credential] token],
                                                                         @"expiresIn": @([@([[[userInfo credential] expired] timeIntervalSinceNow]) longLongValue]),
                                                                         @"platform": platform
                                                                         };
                                   [subject sendNext:[RACTuple tupleWithObjects:userInfoParam, authenticationParam, nil]];
                                   [subject sendCompleted];
                               } else {
//                                   [subject sendError:[[NSError alloc] initWithDomain:@"YTX" code:[error errorCode] userInfo:@{YTX_ERROR_MESSAGE_KEY:[error errorDescription]}]];
                                   [subject sendError:[[NSError alloc] initWithDomain:SHARE_SDK_ERROR_DOMAIN code:[error errorCode] userInfo:@{EFS_ERROR_MESSAGE_KEY:@"绑定失败"}]];
                               }
                           }];
    return subject;
}

+ (RACSignal *)cancelOpenAuthorizations {
    RACReplaySubject *subject = [RACReplaySubject subject];
    if ([ShareSDK hasAuthorizedWithType:ShareTypeSinaWeibo]) {
        [ShareSDK cancelAuthWithType:ShareTypeSinaWeibo];
    }
    if ([ShareSDK hasAuthorizedWithType:ShareTypeQQSpace]) {
        [ShareSDK cancelAuthWithType:ShareTypeQQSpace];
    }
    if ([ShareSDK hasAuthorizedWithType:ShareTypeWeixiSession]) {
        [ShareSDK cancelAuthWithType:ShareTypeWeixiSession];
    }
    [subject sendNext:nil];
    [subject sendCompleted];
    return subject;
}

+ (NSString *)MapType:(ShareType)type
{
    if(type == ShareTypeSinaWeibo)
    {
        return SHARE_TARGET_SINA;
    }
    else if(type == ShareTypeWeixiSession)
    {
        return SHARE_TARGET_WECHATFRIENDS;
    }
    else if(type == ShareTypeWeixiTimeline)
    {
        return SHARE_TARGET_WECHATCIRCLE;
    }
    else if(type == ShareTypeWeixiFav)
    {
        return SHARE_TARGET_WECHATCOLLECTION;
    }
    else if(type == ShareTypeQQ)
    {
        return SHARE_TARGET_QQ;
    }
    else if(type == ShareTypeQQSpace)
    {
        return SHARE_TARGET_QZONE;
    }
    else if(type == ShareTypeMail)
    {
        return SHARE_TARGET_EMAIL;
    }
    else if(type == ShareTypeSMS)
    {
        return SHARE_TARGET_SMS;
    }
    return @"";
}

+ (RACSignal *)shareContentWithInfo: (NSDictionary *)info
{
    RACReplaySubject *subject = [RACReplaySubject subject];
    NSString *content = info[@"content"];
    NSString *title = [info[@"title"] length]?info[@"title"]:@" ";
    NSString *url = info[@"url"];
    if (!content || [content isEqualToString:@""]) {
        content = @"引立文化。";
    }
    // default image
    id<ISSCAttachment> imageAttachment = [ShareSDK pngImageWithImage:[UIImage imageNamed:@"share_icon"]];
    
    NSString *imageUrl = P(@"shareIconUrl");
    if (info[@"imageUrl"] != nil && ![info[@"imageUrl"] isEqualToString:@""]) {
        imageUrl = info[@"imageUrl"];
        imageAttachment = [ShareSDK imageWithUrl:imageUrl];
    }
    if (info[@"image"] != nil && ![info[@"image"] isEqualToString:@""]) {
        imageUrl = info[@"image"];
        imageAttachment = [ShareSDK imageWithUrl:imageUrl];
    }
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:content
                                       defaultContent:content
                                                image:imageAttachment
                                                title:title
                                                  url:url
                                          description:P(@"appname")
                                            mediaType:SSPublishContentMediaTypeNews];

    [publishContent addSMSUnitWithContent: [NSString stringWithFormat:@"%@ （分享自@引立文化  客户端） %@",title,url]];
    /** 添加QQ空间内容单元 图片 + 标题 + 内容 + 链接*/
    [publishContent addQQSpaceUnitWithTitle:INHERIT_VALUE
                                        url:INHERIT_VALUE
                                       site:nil
                                    fromUrl:nil
                                    comment:nil
                                    summary:content
                                      image:INHERIT_VALUE
                                       type:INHERIT_VALUE
                                    playUrl:nil
                                       nswb:@1];
    
    [self addList:publishContent];

    //构造复制内容
    NSString* copyString = [NSString stringWithFormat:@"%@（分享自@引立文化 客户端） %@", title, url];
    id<ISSContent> copyContent = [ShareSDK content:copyString
                                    defaultContent:copyString
                                             image:nil
                                             title:title
                                               url:copyString
                                       description:P(@"appname")
                                         mediaType:SSPublishContentMediaTypeNews];
    
    id<ISSShareActionSheetItem> copyItem = [ShareSDK shareActionSheetItemWithTitle:@"复制链接"
                                                                              icon:[ShareSDK getClientIconWithType:ShareTypeCopy]
                                                                      clickHandler:^{
                                                                          [ShareSDK shareContent:copyContent
                                                                                            type:ShareTypeCopy
                                                                                     authOptions:nil
                                                                                   statusBarTips:YES
                                                                                          result:[self resultWithSignal:subject]];
                                                                      }];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    //选择需要分享的类型
    NSMutableArray *array = [NSMutableArray arrayWithArray:
                             [ShareSDK getShareListWithType:
                              ShareTypeWeixiSession,
                              ShareTypeWeixiTimeline,
                              ShareTypeQQ,
                              ShareTypeQQSpace,
                              nil]];
//    [array insertObject:sinaItem atIndex:4];
    [array addObject:copyItem];
    NSArray* shareList = [NSArray arrayWithArray:array];
    RACSignal * ret = [self showShareActionSheet:container withPublishContent:publishContent withShareList:shareList withId:info[@"id"] withType:info[@"type"] withSignal:subject];
    return ret;
}

+ (RACSignal *)shareContentWithImage: (UIImage *)image andTitle:(NSString *)title
{
    RACReplaySubject *subject = [RACReplaySubject subject];
    id<ISSCAttachment> imageAttachment = [ShareSDK pngImageWithImage:[UIImage imageNamed:@"share_icon"]];
    
    if (image != nil) {
        imageAttachment = [ShareSDK pngImageWithImage:image];
    }
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:@""
                                       defaultContent:@""
                                                image:imageAttachment
                                                title:title
                                                  url:@""
                                          description:@"银如意"
                                            mediaType:SSPublishContentMediaTypeImage];
    
    /** 添加QQ空间内容单元 图片 + 标题 + 内容 + 链接*/
    [publishContent addQQUnitWithType:[NSNumber numberWithInt:SSPublishContentMediaTypeImage]
                              content:INHERIT_VALUE
                                title:INHERIT_VALUE
                                  url:INHERIT_VALUE
                                image:imageAttachment];
    
    
    [self addList:publishContent];
    
      id<ISSShareActionSheetItem> copyItem = [ShareSDK shareActionSheetItemWithTitle:@"复制链接"
                                                                              icon:[ShareSDK getClientIconWithType:ShareTypeCopy]
                                                                      clickHandler:^{
                                                                          [ShareSDK shareContent:publishContent
                                                                                            type:ShareTypeCopy
                                                                                     authOptions:nil
                                                                                   statusBarTips:YES
                                                                                          result:[self resultWithSignal:subject]];
                                                                      }];

    
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    
    //选择需要分享的类型
    NSMutableArray *array = [NSMutableArray arrayWithArray:
                             [ShareSDK getShareListWithType:
                              ShareTypeWeixiSession,
                              ShareTypeWeixiTimeline,
                              ShareTypeQQ,
                              nil]];
    [array addObject:copyItem];
    NSArray* shareList = [NSArray arrayWithArray:array];
    return [self showShareActionSheet:container withPublishContent:publishContent withShareList:shareList withId:nil withType:nil withSignal:subject];
}

+ (id<ISSContent>)addList:(id<ISSContent>)publishContent{
    /** QQ相关Content 图片 + 标题 + 内容 + 链接*/
    [publishContent addQQUnitWithType:INHERIT_VALUE
                              content:INHERIT_VALUE
                                title:INHERIT_VALUE
                                  url:INHERIT_VALUE
                                image:INHERIT_VALUE];
    
    /** 订制微信好友 图片 + 标题 + 内容 + 链接*/
    [publishContent addWeixinSessionUnitWithType:INHERIT_VALUE
                                         content:INHERIT_VALUE
                                           title:INHERIT_VALUE
                                             url:INHERIT_VALUE
                                      thumbImage:INHERIT_VALUE
                                           image:INHERIT_VALUE
                                    musicFileUrl:nil
                                         extInfo:nil
                                        fileData:nil
                                    emoticonData:nil];
    
    /** 订制微信朋友圈 图片 + 标题 + 内容 + 链接*/
    [publishContent addWeixinTimelineUnitWithType:INHERIT_VALUE
                                          content:INHERIT_VALUE
                                            title:INHERIT_VALUE
                                              url:INHERIT_VALUE
                                       thumbImage:INHERIT_VALUE
                                            image:INHERIT_VALUE
                                     musicFileUrl:nil
                                          extInfo:nil
                                         fileData:nil
                                     emoticonData:nil];
    return publishContent;
}

+(RACSignal *) showShareActionSheet:(id<ISSContainer>) container withPublishContent:(id<ISSContent>) publishContent withShareList:(NSArray *) shareList withId:(NSString *) sid withType:(NSString *) stype withSignal:(RACSubject*)subject
{
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:shareList
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:[self resultWithSignal:subject]];
    return subject;
}

+ (SSPublishContentEventHandler)resultWithSignal:(RACSubject*)subject{
    return ^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSResponseStateSuccess)
        {
            [subject sendNext:@{@"shareType":@(type), @"message": type == ShareTypeCopy ? @"拷贝成功" : @"分享成功"}];
            [subject sendCompleted];
        }
        else if (state == SSResponseStateFail)
        {
            [subject sendError:[[NSError alloc] initWithDomain:SHARE_SDK_ERROR_DOMAIN code:[error errorCode] userInfo:@{EFS_ERROR_MESSAGE_KEY: type == ShareTypeCopy ? @"拷贝失败" : @"分享失败"}]];
        }
//        else if (state == SSResponseStateCancel)
//        {
//            [subject sendError:[[NSError alloc] initWithDomain:SHARE_SDK_ERROR_DOMAIN code:[error errorCode] userInfo:@{EFS_ERROR_MESSAGE_KEY: @"分享取消"}]];
//        }
    };
}
+ (SinaPublishResult)sinaResultWithSignal:(RACSubject*)subject{
    return ^(SSResponseState state, id<ISSPlatformShareInfo> status, CMErrorInfo *error) {
        if (state == SSResponseStateSuccess)
        {
            [subject sendNext:@{@"shareType":@(ShareTypeSinaWeibo), @"message": @"分享成功"}];
            [subject sendCompleted];
        }
        else if (state == SSResponseStateFail)
        {
            [subject sendError:[[NSError alloc] initWithDomain:SHARE_SDK_ERROR_DOMAIN code:[error errorCode] userInfo:@{EFS_ERROR_MESSAGE_KEY:@"分享失败"}]];
        }
        else if (state == SSResponseStateCancel)
        {
            [subject sendError:[[NSError alloc] initWithDomain:SHARE_SDK_ERROR_DOMAIN code:[error errorCode] userInfo:@{EFS_ERROR_MESSAGE_KEY: @"分享取消"}]];
        }
    };
}
@end
